package com.jeff.android.lab.arouse;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.jeff.android.lab.AppApplication;
import com.jeff.android.lab.SplashActivity;
import com.jeff.android.lab.architecture.eventbus.event.MessageEvent;
import com.jeff.android.lab.module.widget.webview.WebViewFragment;
import com.jeff.android.lab.util.RouterUtil;
import com.jeff.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;

/**
 *
 * <a href="intent://target#Intent;scheme=android-lab;package=com.jeff.android.lab;end">打开App-1</a>
 *
 * <a href="intent://url=https://www.baidu.com#Intent;scheme=android-lab;package=com.jeff.android.lab;end">打开网页</a>
 *
 * @author: dingfeng
 * @date: 2020-06-04
 * @since: 1.0.0
 **/
public class SchemaActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        final String url = intent != null ? intent.getDataString() : "";

        if (AppApplication.getInstance().isRunning()) {
            redirectUrl(url);
        } else {
            RouterUtil.launchActivity(this, SplashActivity.class);
            // 发送粘性事件
            EventBus.getDefault().postSticky(new MessageEvent(10008, url));
        }
        finish();
    }

    private boolean redirectUrl(String url) {
        if (TextUtils.isEmpty(url))
            return false;

        LogUtil.d("dingfeng", "redirectUrl:" + url);

        if (url.startsWith("android-lab://url")) {
            final String realUrl = url.substring("android-lab://url".length() + 1);
            Bundle bundle = new Bundle();
            bundle.putString("data", realUrl);
            RouterUtil.launchFragmentActivity(this, WebViewFragment.class, bundle);
            return true;
        } else if (url.startsWith("android-lab://target")) {
            RouterUtil.launchActivity(this, SkipTargetActivity.class);
            return true;
        }

        return false; // 没有消费该 url
    }

}
